<?php
/**
 * Seminar translation consists of the translation of seminar texts and names of its batches.
 */
class SeminarTranslation_Controller extends AdminController {

    public $REGISTRATION_LIST_UUID = 'admin/seminarTranslation/list';
    
    /** @var SeminarAccountsData */
    public $data;
    
    public function __construct() {
        parent::__construct('seminar');
        $this->setDefaultListOrder('seminar_id');
        
        $this->data = $this->getSessionData()->getSeminarAccountsData();
    }
    
    public function listing() {
        $seminar = $this->getSeminar();
        
        // Find all translations of the seminar
        $this->viewData['seminarTranslationList'] = $this->dao->queryAll($this->orderLimitAndOffset(
                'SELECT sl10n.*, l.name as language_name FROM seminar_l10n sl10n ' .
                'JOIN language l ON l.code = sl10n.language_code ' .
                'WHERE sl10n.seminar_id = :seminarId'),
                array('seminarId' => $seminar['id']));
        
        $this->renderMySubview('seminarTranslationList');
    }
    
    function display() {
        $seminarId = $this->input->get('seminar_id');
        $languageCode = $this->input->get('language_code');

        if (! valid::isId($seminarId) || ! valid::isCode($languageCode)) {
            $this->redirectToList('error.invalidId');
        }

        $this->viewData['seminar'] = $this->dao->getLocalizedEntityById('seminar', $seminarId, $this->getLocalLanguageCode());
        if (! $this->viewData['seminar']) {
            $this->redirectToList('error.recordNotFound');
        }
        
        $this->viewData['language'] = $this->dao->getByCode('language', $languageCode);
        
        $seminarTranslation = $this->dao->getLocalizedEntityById('seminar', $seminarId, $languageCode);
        
        $this->viewData['seminarTranslation'] = $seminarTranslation;
        if (! $seminarTranslation) {
            $this->redirectToList('error.recordNotFound');
        }
        
        $this->loadBatches($seminarId, $languageCode);
        $this->renderSubview('admin/seminarTranslation/seminarTranslationDisplay');
    }
    
    private function loadBatches($seminarId, $languageCode) {
    	if (! $languageCode) {
    		$languageCode = $this->getLocalLanguageCode();
    	}
    	$batchTypeList = $this->dao->queryAll(
    			'SELECT DISTINCT bt.code, l10n.name ' .
    			'FROM batch b ' .
    			'JOIN batch_type bt ON b.batch_type_code = bt.code ' .
    			'LEFT OUTER JOIN batch_type_l10n l10n ON bt.code = l10n.batch_type_code AND l10n.language_code = :lang ' .
    			'WHERE b.seminar_id = :seminar_id ' .
    			'ORDER BY bt.code',
    			array('seminar_id' => $seminarId, 'lang' => $languageCode));
    	
    	foreach ($batchTypeList as &$batchType) {
    		$batchType['batchList'] = $this->dao->queryAll(
    				'SELECT b.*, l10n.name, loc.name AS name_local ' .
    				'FROM batch b ' .
    				'LEFT OUTER JOIN batch_l10n l10n ON b.batch_code = l10n.batch_code AND l10n.seminar_id = :seminarId AND l10n.language_code = :lang ' .
    				'LEFT OUTER JOIN batch_l10n loc ON b.batch_code = loc.batch_code AND loc.seminar_id = :seminarId AND loc.language_code = :langLocal ' .
    				'WHERE b.seminar_id = :seminarId ' .
    				'AND b.batch_type_code = :batch_type_code ' .
    				'ORDER BY b.begin_date',
    				array(
    						'seminarId' => $seminarId,
    						'lang' => $languageCode,
    						'langLocal' => $this->getLocalLanguageCode(),
    						'batch_type_code' => $batchType['code']));
    	}
    	$this->viewData['batchTypeList'] = $batchTypeList;
    	return $batchTypeList;
    }
    
    public function edit() {
        $seminar = $this->getSeminar();
        $languageCode = $_GET['language_code'];

        if (valid::isCode($languageCode)) {
            $formData = $this->dao->getUnique('seminar_l10n',
                    array(
                        'seminar_id' => $seminar['id'],
                        'language_code' => $languageCode
                    ));
            if (! $formData) {
                $this->redirectToList('error.recordNotFound');
            }
            $batchList = $this->dao->queryAll(
    				'SELECT b.batch_code, l10n.name ' .
    				'FROM batch b ' .
    				'LEFT OUTER JOIN batch_l10n l10n ON b.batch_code = l10n.batch_code AND l10n.seminar_id = :seminarId AND l10n.language_code = :lang ' .
    				'WHERE b.seminar_id = :seminarId ' .
    				'ORDER BY b.begin_date',
    				array('seminarId' => $seminar['id'], 'lang' => $languageCode));
            foreach ($batchList as $batch) {
            	$formData['batch_' . $batch['batch_code']] = $batch['name'];
            }
        }
        else {
            // Default values
            $formData = array('seminar_id' => $seminar['id']);
        }
        $localTranslation = $this->dao->getLocalizedEntityById('seminar', $seminar['id'], $this->getLocalLanguageCode());
        $formData['name_local'] = $localTranslation['name'];
        $formData['description_local'] = $localTranslation['description'];
        $this->viewData['formData'] = $formData;

        $this->loadFormData($seminar, $languageCode);
        $this->renderMySubview('seminarTranslationEdit');
    }

    function loadFormData($seminar, $languageCode) {
        $params = array('seminar_id' => $seminar['id']);
        $query = 'SELECT l.code, l.name ' .
                    'FROM language l ' .
                    'WHERE l.code NOT IN (SELECT l10n.language_code FROM seminar_l10n l10n WHERE l10n.seminar_id = :seminar_id) ';
        if ($languageCode) {
            $query .= 'OR l.code = :language_code ';
            $params['language_code'] = $languageCode;
        }
        $query .= 'ORDER BY l.name';
        $this->viewData['languageOptions'] = $this->dao->queryOptions($query, $params);
        
        $this->loadBatches($seminar['id'], $languageCode);
    }

    function save() {
        $formData = $this->postToDbValues();
        $this->viewData['formData'] = $formData;
        $seminar = $this->getSeminar();
        $languageCode = $formData['language_code'];

        // Basic validation
        $validator = new EntityValidator($formData, 'seminar', $this->msg);
        $validator->code('language_code', 'common-language');
        $validator->required('name');
        $validator->required('description');
        if ($this->msg->hasErrors()) {
            $this->loadFormData($seminar, $languageCode);
            $this->publishErrors('admin/seminarTranslation/edit');
            return;
        }

        $language = $this->dao->getByCode('language', $languageCode);
        if (! $language) {
            $this->redirectToList('error.recordNotFound');
        }

        $entity = new SeminarL10nEntity($formData);
        
        if (! $entity->isPersistent()) {
            // Check if we don't have already this language
            $existingL10n = $this->dao->getByPrimaryKey($entity);
            if ($existingL10n) {
                $this->msg->error('errors.translationAlreadyExists', $language['name']);
                $this->loadFormData($seminar, $languageCode);
                $this->publishErrors('admin/seminarTranslation/edit');
            }

            $this->dao->insertEntity($entity);
            $this->msg->info('seminarTranslation.createSuccess', $language['name']);
        }
        else {
            $this->dao->updateEntity($entity);
            $this->msg->info('seminarTranslation.editSuccess', $language['name']);
        }
        
        foreach ($formData as $fieldName => $value) {
        	if (substr($fieldName, 0, 6) == 'batch_') {
        		$batchCode = substr($fieldName, 6);
        		$translation = $this->dao->getUnique('batch_l10n', array('seminar_id' => $seminar['id'], 'batch_code' => $batchCode, 'language_code' => $languageCode));
        		if ($translation) {
        			$translation['name'] = $value;
        			$entity = new BatchL10nEntity($translation);
        			$this->dao->updateEntity($entity);
        		}
        		else {
        			$entity = new BatchL10nEntity(array(
        					'seminar_id' => $seminar['id'],
        					'batch_code' => $batchCode,
        					'language_code' => $languageCode,
        					'name' => $value));
        			$this->dao->insertEntity($entity);
        		}
        	}
        }

        $this->redirect('/admin/seminarTranslation/listing?seminar_id=' . $seminar['id']);
    }

    function deleteLocalizedValues() {
        $seminar = $this->getSeminar();
        $languageCode = $this->input->get('language_code');

        if (! valid::isCode($languageCode)) {
            $this->redirectToList('error.invalidId');
        }
        $language = $this->dao->getByCode('language', $languageCode);
        if (! $language) {
            $this->redirectToList('error.recordNotFound');
        }

        $entity = new SeminarL10nEntity($_GET);

        $existingRecord = $this->dao->getByPrimaryKey($entity);
        if (! $existingRecord) {
            $this->redirectToList('error.recordNotFound');
        }

        $this->dao->deleteEntity($entity);

        $this->msg->info('seminarTranslation.deleteSuccess', $language['name']);
        $this->redirect('/admin/seminarTranslation/display?seminar_id=' . $seminar['id']);
    }
    
    private function getSeminar() {
    	$seminarId = $this->input->get('seminar_id');
    	if (! $seminarId) {
    		$seminarId = $this->input->post('seminar_id');
    	}
    	if (! valid::isId($seminarId)) {
    		$this->redirectToList('error-invalidId');
    	}
    		
    	$seminar = $this->dao->fetchSeminar($seminarId, $this->getL10nLanguageCode());
    	if (! $seminar) {
    		$this->redirectToList('error-recordNotFound');
    	}
    	$this->viewData['seminar'] = $seminar;
    	return $seminar;
    }
    
    protected function redirectToList($errorKey=NULL) {
        if ($errorKey) {
            $this->msg->error($errorKey);
        }
        $this->redirect('/admin/seminar/all');
    }
}